<template>
  <div class="hello">
    <div class="common_center">
      <div class="map_all">
        <el-amap vid="amap" :amap-manager="amapManager" :plugin="plugin"  :zoom="zoom" :events="events" :center="center">
          <el-amap-marker vid="component-marker" :position="componentMarker.position" :events="componentMarker.events" ><span @click="alert(1)"></span></el-amap-marker>
          <el-amap-marker v-for="(marker, index) in filteredMarkers" :position="marker.position" :icon="icon" :events="markerEvents"  :visible="true" :draggable="false"
            :key="index" :vid="index" :label="marker.deviceName" :title="marker.deviceName + marker.memo + marker.telephone"></el-amap-marker>
            <el-amap-info-window
          :position="currentWindow.position"
          :content="currentWindow.content"
          :visible="isWinVisiable"
          :events="currentWindow.events">
        </el-amap-info-window>

        </el-amap>
        <div class="toolbar">
          <span v-if="loaded">
            已定位
            <!-- location: lng = {{ lng }} lat = {{ lat }} -->
          </span>
          <span v-else>正在定位</span>
          © 2018 河南工业贸易职业学院
        </div>
         <div class="lineSelect form-control">
          <select name="selected" @change='changeLine'><option value="-1" selected> 全部线路</option><option value="1"> 东线</option><option value="2"> 中线</option>
          <option value="3"> 西线</option>
          </select>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import { AMapManager } from 'vue-amap'
import { Toast } from 'mint-ui'
let amapManager = new AMapManager()
export default {
  name: 'app',
  data() {
    let self = this
    return {
      amapManager,
      start: false,
      timeOut: '',
      interval: 3000,
      center: [113.685502, 34.631236],
      lng: 0,
      lat: 0,
      lineid: -1,
      loaded: false,
      isWinVisiable: false,
      zoom: 16,
      icon: require('../assets/gps_icon/01.png'),
      markers: [
        {
          position: [113.563195529514, 34.820390896268],
          lineid: 1,
          termid: 1,
          deviceName: '1号专车',
          memo: '豫A88888',
          telephone: '13012341234'
        }
      ],
      currentWindow: {
        position: [113.563195529514, 34.820390896268],
        content: '信息窗体',
        events: {
          close: () => {
            this.isWinVisiable = false
            // console.log('ddddddd'+this.isWinVisiable)
          }
        }
      },
      markerEvents: {
        click: e => {
          // console.log(e.lnglat)
          console.log(e.target.Ch.vid)
          this.currentWindow.position = [e.lnglat.lng, e.lnglat.lat]
          this.isWinVisiable = true
          this.currentWindow.content =
            '<div>' +
            this.filteredMarkers[e.target.Ch.vid].deviceName +
            '</br>' +
            this.filteredMarkers[e.target.Ch.vid].memo +
            '</br>' +
            this.filteredMarkers[e.target.Ch.vid].telephone +
            '</b-alert>'
        }
      },
      events: {
        init(map) {}
      },
      componentMarker: {
        position: [113.685502, 34.631236],
        events: {
          click: () => {
            alert('这里是河南工业贸易职业技术学院喔！')
          }
        }
      },
      plugin: [
        {
          pName: 'Geolocation',
          buttonPosition: 'LB',
          zoomToAccuracy: true,
          timeout: 10000,
          maximumAge: 10000,
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  self.lng = result.position.lng
                  self.lat = result.position.lat
                  self.center = [self.lng, self.lat]
                  // console.log(result.message)
                  // console.log(result.formattedAddress)
                  localStorage.setItem('mylocation', result.formattedAddress)
                  localStorage.setItem('position', result.position)
                  if (!self.loaded) {
                    Toast({
                      message: '您的当前位置：' + result.formattedAddress,
                      position: 'bottom',
                      duration: 3000
                    })
                  }
                  self.loaded = true
                  self.$nextTick()
                }
              })
              // 定时获取用户位置
              setInterval(() => {
                o.getCurrentPosition((status, result) => {
                  if (result && result.position) {
                    self.lng = result.position.lng
                    self.lat = result.position.lat
                    self.center = [self.lng, self.lat]
                    self.loaded = true
                    // console.log(result.message)
                    // console.log(result.formattedAddress)
                    localStorage.setItem('mylocation', result.formattedAddress)
                    localStorage.setItem('position', result.position)

                    let smallDistMarker = self.markers[0]
                    let smallDist = 0
                    let tmpDist = 0
                    for (var i = 0; i < self.markers.length; i++) {
                      tmpDist = AMap.GeometryUtil.distance(
                        result.position,
                        self.markers[i].position
                      )
                      if (i == 0) {
                        smallDistMarker = self.markers[i]
                        smallDist = tmpDist
                      } else {
                        if (tmpDist < smallDist) {
                          smallDistMarker = self.markers[i]
                          smallDist = tmpDist
                        }
                      }
                    }
                    let arriveTime = smallDist / 8.33 / 60
                    Toast({
                      message: `离您最近的车辆为：${
                        smallDistMarker.deviceName
                      }，距离为：${Math.round(smallDist)}米，预计${Math.round(arriveTime)}分钟后到达。`,
                      position: 'bottom',
                      duration: 3000
                    })
                    self.$nextTick()
                  }
                })
              }, 10000)
            }
          }
        },
        {
          pName: 'Scale',
          position: 'LB',
          events: {
            init(o) {
              // console.log(o)
            }
          }
        },
        {
          pName: 'MapType',
          position: 'LB',
          // position: {top: '100px', right: '20px'},
          events: {
            init(o) {
              // console.log(o)
            }
          }
        },
        {
          pName: 'ToolBar',
          position: 'RB',
          events: {
            init(o) {
              // console.log(o)
            }
          }
        }
      ]
    }
  },
  computed: {
    // 计算属性的 getter
    filteredMarkers: function() {
      // `this` 指向 vm 实例
      // console.log(this.markers)
      var filterMarks = []
      if (this.lineid !== -1) {
        filterMarks = []
        for (var i = 0; i < this.markers.length; i++) {
          if (this.markers[i].lineid == this.lineid) {
            filterMarks.push(this.markers[i])
          }
        }
      }
      if (this.lineid.valueOf() == -1) {
        console.log('全部线路')
        if (filterMarks.length > 0) {
          filterMarks.splice(0, filterMarks.length)
        }
        for (var j = 0; j < this.markers.length; j++) {
          filterMarks.push(this.markers[j])
        }
      }
      console.log('过滤结果：')
      console.log(filterMarks)
      return filterMarks
    }
  },
  mounted() {
    let _this = this
    this.$nextTick(function() {
      this.start = true
      this.getListIng()
    })
  },
  methods: {
    openWindow(marker) {
      alert(marker)
      this.currentWindow.visible = true
      this.currentWindow.position = marker.position
      this.currentWindow.content = marker.memo + '</br>' + marker.telephone
      this.currentWindow.events = {
        close() {
          // alert('ddd')
        }
      }
    },
    changeLine: function(ele) {
      // var optionTxt = $(ele.target)
      //   .find('option:selected')
      //   .text()
      var optionVal = ele.target.value
      console.log(optionVal)
      this.lineid = optionVal
    },
    getListIng() {
      // 这里是一个http的异步请求
      let _this = this
      this.axios({
        method: 'post',
        url: '/api/gps/location/amaploc'
      })
        .then(function(response) {
          // console.log(response.data)
          if (response.data.code === 200) {
            _this.markers = response.data.data
          }
        })
        .catch(function(response) {
          console.log(response)
        })
      if (this.start) {
        let _this = this
        this.timeOut = setTimeout(() => {
          _this.getListIng()
        }, _this.interval)
      } else {
        this.timeOut = ''
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
.lineSelect {
  position: fixed;
  bottom: 1%;
  right: 10%;
  z-index: 888;
  width: 60px;
  height: 40px;
  opacity: 0.7;
}
</style>
